﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebNext.Domain.Entities;
using System.Web.Mvc;
using System.Xml.Serialization;
using WebNext.Domain;
using WebNext.UI.Properties;
using WebNext.UI.Utils;

namespace WebNext.UI.Models.Entries
{
	public class EntryCodeElementViewModel : EntryElementViewModel
	{
		public override EntryElementType Type
		{
			get { return EntryElementType.Code; }
		}

		public string Code
		{
			get;
			private set;
		}

		public bool IsCodeValid
		{
			get;
			private set;
		}

		public CodeSnippetType CodeType
		{
			get;
			private set;
		}

		public EntryCodeElementViewModel(EntryCodeElement entryCodeElement) : base(entryCodeElement.Order)
		{
			this.Code = entryCodeElement.Code;
			this.IsCodeValid = true;
			this.CodeType = entryCodeElement.CodeType;
		}

		public EntryCodeElementViewModel(int order, IDictionary<string, string> properties)	: base(order)
		{
			if (properties.ContainsKey("code"))
			{
				this.Code = properties["code"];
			}
			this.IsCodeValid = true;

			if (properties.ContainsKey("codeType"))
			{
				this.CodeType = (CodeSnippetType)Enum.Parse(typeof(CodeSnippetType), properties["codeType"]);
			}
			else
			{
				this.CodeType = CodeSnippetType.CSharp;
			}
		}

		public override EntryElement GetEntryElement()
		{
			return new EntryCodeElement { Code = this.Code, CodeType = this.CodeType, Order = this.Order, Type = this.Type };
		}

		public override ValidationResult Validate()
		{
			ValidationResult result = new ValidationResult();
			if (string.IsNullOrWhiteSpace(this.Code))
			{
				result.AddError(Resources.EntryCodeCannotBeEmpty);
				this.IsCodeValid = false;
			}
			else if (this.Code.Length > EntryCodeElement.MaxCodeLength)
			{
				result.AddError(Resources.EntryCodeTooLong, EntryCodeElement.MaxCodeLength);
				this.IsCodeValid = false;
			}
			return result;
		}
	}
}